package com.am.server.api.system.dictionary.dao.rdb.impl;

import com.am.server.api.system.dictionary.dao.rdb.DictionaryItemDao;
import com.am.server.api.system.dictionary.model.dto.DictionaryItemListQueryDto;
import com.am.server.api.system.dictionary.model.entity.DictionaryItemEntity;
import com.am.server.api.system.dictionary.model.entity.QDictionaryItemEntity;
import com.am.server.api.system.dictionary.repository.DictionaryItemRepository;
import com.querydsl.core.BooleanBuilder;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author 阮雪峰
 */
@Repository
public class DictionaryItemDaoImpl implements DictionaryItemDao {
    private final DictionaryItemRepository dictionaryItemRepository;

    public DictionaryItemDaoImpl(DictionaryItemRepository dictionaryItemRepository) {
        this.dictionaryItemRepository = dictionaryItemRepository;
    }

    @Override
    public List<DictionaryItemEntity> find(DictionaryItemListQueryDto dto) {
        QDictionaryItemEntity entity = QDictionaryItemEntity.dictionaryItemEntity;
        Optional<DictionaryItemListQueryDto> optional = Optional.of(dto);

        BooleanBuilder booleanBuilder = new BooleanBuilder(entity.id.isNotNull());
        optional.map(DictionaryItemListQueryDto::getName).ifPresent(obj -> booleanBuilder.and(entity.name.contains(obj)));
        optional.map(DictionaryItemListQueryDto::getDictionaryId).ifPresent(obj -> booleanBuilder.and(entity.dictionary.id.eq(obj)));
        optional.map(DictionaryItemListQueryDto::getDictionaryCode).ifPresent(obj -> booleanBuilder.and(entity.dictionary.code.eq(obj)));

        return (List<DictionaryItemEntity>) dictionaryItemRepository.findAll(Objects.requireNonNull(booleanBuilder.getValue()), Sort.by(Sort.Direction.ASC, entity.sort.getMetadata().getName(), entity.id.getMetadata().getName()));
    }

    @Override
    public void save(DictionaryItemEntity entity) {
        dictionaryItemRepository.save(entity);
    }

    @Override
    public void delete(Long id) {
        dictionaryItemRepository.deleteById(id);
    }

    @Override
    public Optional<DictionaryItemEntity> findById(Long id) {
        return dictionaryItemRepository.findById(id);
    }
}
